var express = require('express');
var router = express.Router();
var qs = require('querystring');
var myUtil = require('../utils/myUtil.js');
var checker = require('../utils/myDataChecker.js');

// 
router.post("/", function(req, res) {
	var body = "";
	req.on("data", function(chunk) {
		body += chunk;
	});

	req.on('end', function() {
		var json = parseInput(body);
		if (json.data) {
			verifyUser(req.db, json.data, function(isOk, errMsg) {
				var result;
				if (isOk) {
					result = myUtil.resJsonOk(null);
				} else {
					result = myUtil.resJsonErr(errMsg);
				}
				res.send(JSON.stringify(result));
			});
		} else {
			res.send(JSON.stringify(json));
		}
	});
});

var template = {
	"id": "xxx",
	"password": "xxx"
};

function parseInput(data) {
	var json = myUtil.str2Json(data);
	if (!json) {
		return myUtil.resJsonErr("canot parse to json");
	}
	
	var checkResult = myDataChecker.check(template, json);
	if (checkResult.isOk === false) {
		return myUtil.resJsonErr(checkResult.msg);
	}

	return myUtil.resJsonOk(json);
}

function verifyUser(db, data, callback) {
	var collection = db.get("user");
	collection.findOne({
		"id": data.id
	}, function(err, doc) {
		if (err) {
			console.log("verifyUser err");
			callback(false, err);
		} else if (!doc) {
			console.log("not register: id=" + data.id);
			callback(false, "not register yet");
		} else if (doc.password !== data.password) {
			console.log("wrong password: id=" + data.id);
			callback(false, "wrong password");
		} else {
			callback(true);
		}
	});
}


module.exports = router;